package com.randi.common.core.domain.entity;

import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.randi.common.annotation.Excel;
import com.randi.common.config.AppConfig;
import com.randi.common.core.domain.BaseEntity;
import com.randi.common.serializer.LongsToStringSerializer;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.data.annotation.Transient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Set;

/**
 * @author ziye
 */
@EqualsAndHashCode(callSuper = true)
@Data
@Component
@TableName("sys_role")
@ApiModel(value = "SysRole", description = "系统角色对象")
public class SysRole extends BaseEntity {

    @TableId(value = "role_id", type = IdType.ASSIGN_ID)
    @JsonSerialize(using = ToStringSerializer.class)
    @ApiModelProperty(value = "角色ID")
    @Excel(name = "角色ID")
    private Long roleId;

    @NotBlank(message = "角色名称不能为空")
    @TableField(value = "`role_name`")
    @ApiModelProperty(value = "角色名称")
    @Excel(name = "角色名称")
    private String roleName;

    @NotBlank(message = "角色权限不能为空")
    @TableField(value = "`role_key`")
    @ApiModelProperty(value = "角色权限")
    @Excel(name = "角色权限")
    private String roleKey;

    @NotBlank(message = "显示顺序不能为空")
    @TableField(value = "`role_sort`")
    @ApiModelProperty(value = "显示顺序")
    @Excel(name = "显示顺序")
    private Integer roleSort;

    @TableField(exist = false)
    @ApiModelProperty(value = "菜单Id")
    @JsonSerialize(using = LongsToStringSerializer.class)
    private List<Long> menuIds;

    @TableField(exist = false)
    @ApiModelProperty(value = "角色菜单权限")
    @Excel(name = "角色菜单权限")
    private Set<String> permissions;

    private static Long adminId;

    @Resource
    private void init(AppConfig.SystemConfig systemConfig) {
        adminId = systemConfig.getRoleAdminId();
    }

    @Transient
    public String getKey() {
        return this.roleId == null ? "" : this.roleId.toString();
    }

    @Transient
    public boolean isAdmin() {
        return isAdmin(this.roleId);
    }

    @Transient
    public static boolean isAdmin(Long roleId) {
        return roleId != null && roleId.equals(adminId);
    }

}
